package com.youth.orderservice.mq.Consumers;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import com.youth.commonutils.R;
import com.youth.commonutils.RedisConstants;
import com.youth.orderservice.Client.CourseClient;
import com.youth.orderservice.Client.UserClient;
import com.youth.orderservice.entity.TOrder;
import com.youth.orderservice.entity.TPayLog;
import com.youth.orderservice.mapper.TOrderMapper;
import com.youth.orderservice.mapper.TPayLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrRef;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Component
public class payOrderConsumer {

    @Autowired
    private UserClient userClient;

    @Autowired
    private CourseClient courseClient;

    @Autowired
    private TPayLogMapper tPayLogMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private TOrderMapper tOrderMapper;

    public static final String QUEUE_B = "QB";

    @Transactional
    @RabbitListener(queues = QUEUE_B)
    public void receiveB(Message message, Channel channel){
        String s = new String(message.getBody());
        TOrder tOrder = JSON.parseObject(s, TOrder.class);
        /*1.扣减用户金额*/
        boolean flag1 = userClient.subtract(tOrder.getMemberId(), tOrder.getPrice().toString());
        /*2.操作pay日志表*/
        TPayLog tPayLog = new TPayLog();
        tPayLog.setOrderNo(tOrder.getOrderNo());
        tPayLog.setTotalFee(tOrder.getPrice());
        int insert = tPayLogMapper.insert(tPayLog);
        /*3.操作course_member表*/
        boolean flag2 = courseClient.insertCourseMember(tOrder.getCourseId(), tOrder.getMemberId());
        /*4.修改订单的状态*/
        tOrder.setStatus(1);
        tOrderMapper.update(tOrder,new QueryWrapper<TOrder>().eq("order_no", tOrder.getOrderNo()));
        /*4.操作redis,一个课程一个用户只能购买一次*/
        if (insert>0 && flag1==true && flag2==true){
            String redisKey= RedisConstants.COURSE+tOrder.getCourseId();
            stringRedisTemplate.opsForSet().add(redisKey,tOrder.getMemberId());
        }
    }

}